package com.hxzy.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author wzm
 * @create 2023-09-20 15:29
 * project_name:javaweb2308
 */
public class BaseServlet extends HttpServlet {
    //重写父类的Servlet自定义Service方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //根据/user/xxx  xxx来判断执行哪个方法  /user/update

        try {
            //1.获取到请求地址 uri  /web06/user/add
            String uri = req.getRequestURI();
            System.out.println("uri = " + uri);

            //2.根据路径截取到最后要执行的方法 add
            String methodName = uri.substring(uri.lastIndexOf('/') + 1);

            //3.根据方法名通过反射获取方法 add()
            Class<? extends BaseServlet> cla = this.getClass();
            //获取方法对象
            Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

            //4.执行该方法
            method.setAccessible(true);//开启临时访问权限
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }


}
